package org.example.mybatis3.config;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.mybatis3.entity.User;
import org.example.mybatis3.entity.blog.Author;
import org.example.mybatis3.entity.blog.Blog;
import org.example.mybatis3.entity.blog.Post;
import org.example.mybatis3.entity.discriminator.*;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

//@Configuration
public class MyBatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        // 创建 MyBatis 配置对象并设置相关属性
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);
        configuration.setLogImpl(StdOutImpl.class); // 对应 STDOUT_LOGGING
        configuration.setMapUnderscoreToCamelCase(true);

        // 手动注册特定的类型别名
        configuration.getTypeAliasRegistry().registerAlias("User", User.class);
        configuration.getTypeAliasRegistry().registerAlias("Blog", Blog.class);
        configuration.getTypeAliasRegistry().registerAlias("Author", Author.class);
        configuration.getTypeAliasRegistry().registerAlias("Post", Post.class);
        configuration.getTypeAliasRegistry().registerAlias("Vehicle", Vehicle.class);
        configuration.getTypeAliasRegistry().registerAlias("Car", Car.class);
        configuration.getTypeAliasRegistry().registerAlias("Truck", Truck.class);
        configuration.getTypeAliasRegistry().registerAlias("Van", Van.class);
        configuration.getTypeAliasRegistry().registerAlias("SUV", SUV.class);

        sessionFactory.setConfiguration(configuration);

        return sessionFactory.getObject();
    }
}
